package com.congee02.bt.dfs.top2bottom;

import com.congee02.bt.TreeNode;

import java.util.*;

public class BinaryTreePaths {

    public List<String> binaryTreePaths(TreeNode root) {

        List<String> ans = new ArrayList<>();


        help(root, ans, new ArrayList<>());

        return ans;
    }

    private void help(TreeNode root, List<String> ans, ArrayList<Integer> path) {

        if (root == null) {
            return;
        }

        path.add(root.val);

        if (root.left == null && root.right == null) {
            ans.add(buildPath(path));
        } else {
            help(root.left, ans, path);
            help(root.right, ans, path);
        }

        path.remove(path.size() - 1);
    }

    private String buildPath(ArrayList<Integer> path) {

        StringBuilder builder = new StringBuilder();

        int n = path.size();

        for (int i = 0 ; i < n - 1 ; i ++ ) {
            builder.append(path.get(i)).append("->");
        }
        builder.append(path.get(n - 1));

        return builder.toString();
    }

}
